<template>
  <div class="dashboard">
    <!-- 顶部卡片统计 -->
    <div class="stat-cards">
      <el-row :gutter="20">
        <el-col :span="6" v-for="(stat, index) in statistics" :key="index">
          <el-card class="stat-card" shadow="hover">
            <template #header>
              <div class="card-header">
                <span>{{ stat.title }}</span>
                <el-tooltip :content="stat.tooltip" placement="top">
                  <el-icon><QuestionFilled /></el-icon>
                </el-tooltip>
              </div>
            </template>
            <div class="card-value">{{ stat.value }}</div>
            <div class="card-trend" :class="stat.trend">
              <el-icon>
                <component :is="stat.trend === 'up' ? 'ArrowUp' : 'ArrowDown'" />
              </el-icon>
              {{ stat.percentage }}%
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 控制面板 -->
    <el-card class="control-panel">
      <template #header>
        <div class="card-header">
          <span>数据控制</span>
          <div class="control-actions">
            <el-select v-model="selectedFile" placeholder="选择历史文件" @change="handleFileChange">
              <el-option
                v-for="file in historyFiles"
                :key="file"
                :label="file"
                :value="file"
              />
            </el-select>
            
            <el-select v-model="selectedFeature" placeholder="选择特征" @change="handleFeatureChange">
              <el-option
                v-for="feature in featureNames"
                :key="feature"
                :label="feature"
                :value="feature"
              />
            </el-select>
            
            <el-radio-group v-model="timeRange" size="small" @change="handleTimeRangeChange">
              <el-radio-button value="day">日</el-radio-button>
              <el-radio-button value="week">周</el-radio-button>
              <el-radio-button value="month">月</el-radio-button>
            </el-radio-group>
          </div>
        </div>
      </template>
    </el-card>

    <!-- 主要图表区域 -->
    <div class="main-charts">
      <el-row :gutter="20">
        <el-col :span="16">
          <el-card class="chart-card" v-loading="loading">
            <div class="chart-container">
              <v-chart class="chart" :option="trendOption" autoresize />
            </div>
          </el-card>
        </el-col>
        <el-col :span="8">
          <el-card class="chart-card">
            <div class="chart-container">
              <v-chart class="chart" :option="accuracyOption" autoresize />
            </div>
          </el-card>
        </el-col>
      </el-row>
      
      <el-row>
        <el-col :span="24">
          <el-card class="chart-card" v-if="selectedFeature">
            <div class="chart-container">
              <v-chart class="chart" :option="featureDistributionOption" autoresize />
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { LineChart, PieChart, BarChart } from 'echarts/charts'
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent,
  DataZoomComponent,
  ToolboxComponent
} from 'echarts/components'
import VChart from 'vue-echarts'
import { QuestionFilled, ArrowUp, ArrowDown } from '@element-plus/icons-vue'
import { historyApi } from '@/api'
import { ElMessage } from 'element-plus'

// 注册必要的 ECharts 组件
use([
  CanvasRenderer,
  LineChart,
  PieChart,
  BarChart,
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent,
  DataZoomComponent,
  ToolboxComponent
])

const timeRange = ref('week')
const loading = ref(false)
const historyFiles = ref([])
const selectedFile = ref('')
const fileData = ref([])
const featureNames = ref([])
const selectedFeature = ref('')

// 统计数据
const statistics = ref([
  {
    title: '平均预测误差',
    value: '0.0%',
    trend: 'down',
    percentage: 0,
    tooltip: '相比上周期预测误差降低'
  },
  {
    title: '预测准确率',
    value: '0.0%',
    trend: 'up',
    percentage: 0,
    tooltip: '相比上周期准确率提升'
  },
  {
    title: '预测样本数',
    value: '0',
    trend: 'up',
    percentage: 0,
    tooltip: '累计预测样本数量'
  },
  {
    title: '模型响应时间',
    value: '0.0s',
    trend: 'down',
    percentage: 0,
    tooltip: '平均模型响应时间'
  }
])

// 获取历史文件列表
const fetchHistoryFiles = async () => {
  loading.value = true
  try {
    const response = await historyApi.getHistoryFiles()
    if (response.files && response.files.length > 0) {
      historyFiles.value = response.files
      // 默认选择第一个文件
      selectedFile.value = response.files[0]
      await fetchFileData(selectedFile.value)
    } else {
      ElMessage.info('没有找到历史预测文件')
    }
  } catch (error) {
    ElMessage.error('获取历史文件失败')
    console.error(error)
  } finally {
    loading.value = false
  }
}

// 获取文件数据
const fetchFileData = async (filename) => {
  if (!filename) return
  
  loading.value = true
  try {
    const response = await historyApi.getFileData(filename, 1000) // 获取更多数据用于分析
    if (response.data && response.data.length > 0) {
      fileData.value = response.data
      
      // 提取特征名称（排除时间戳列）
      const firstRow = response.data[0]
      featureNames.value = Object.keys(firstRow).filter(key => key !== 'timestamp')
      
      // 默认选择第一个特征
      if (featureNames.value.length > 0) {
        selectedFeature.value = featureNames.value[0]
      }
      
      // 更新统计数据
      updateStatistics(response.data)
    }
  } catch (error) {
    ElMessage.error('获取文件数据失败')
    console.error(error)
  } finally {
    loading.value = false
  }
}

// 更新统计数据
const updateStatistics = (data) => {
  // 样本数量
  statistics.value[2].value = data.length.toString()
  
  // 如果有实际值和预测值列，计算误差和准确率
  if (data[0].actual && data[0].predicted) {
    const errors = data.map(item => 
      Math.abs((item.predicted - item.actual) / item.actual) * 100
    )
    const avgError = errors.reduce((a, b) => a + b, 0) / errors.length
    const accuracy = 100 - avgError
    
    statistics.value[0].value = `${avgError.toFixed(1)}%`
    statistics.value[1].value = `${accuracy.toFixed(1)}%`
    
    // 假设与上一周期相比的变化
    statistics.value[0].percentage = 5
    statistics.value[1].percentage = 3
  }
  
  // 模拟响应时间
  statistics.value[3].value = '0.5s'
  statistics.value[3].percentage = 10
}

// 趋势图配置
const trendOption = computed(() => {
  const timestamps = fileData.value.map(item => item.timestamp)
  const series = []
  
  if (selectedFeature.value) {
    // 只显示选中的特征
    series.push({
      name: selectedFeature.value,
      type: 'line',
      data: fileData.value.map(item => item[selectedFeature.value]),
      smooth: true
    })
  } else {
    // 显示所有特征
    featureNames.value.forEach(feature => {
      series.push({
        name: feature,
        type: 'line',
        data: fileData.value.map(item => item[feature]),
        smooth: true
      })
    })
  }
  
  return {
    title: {
      text: '预测趋势',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: series.map(s => s.name),
      top: 30
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '10%',
      containLabel: true
    },
    toolbox: {
      feature: {
        saveAsImage: {}
      }
    },
    dataZoom: [
      {
        type: 'slider',
        show: true,
        start: 0,
        end: 100
      }
    ],
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: timestamps
    },
    yAxis: {
      type: 'value'
    },
    series
  }
})

// 准确率饼图配置
const accuracyOption = computed(() => {
  // 从统计数据中获取准确率
  const accuracy = parseFloat(statistics.value[1].value) || 0
  const error = 100 - accuracy
  
  return {
    title: {
      text: '预测准确率',
      left: 'center'
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c}%'
    },
    legend: {
      orient: 'vertical',
      left: 10,
      top: 'center',
      data: ['准确', '误差']
    },
    series: [
      {
        name: '预测结果',
        type: 'pie',
        radius: ['50%', '70%'],
        avoidLabelOverlap: false,
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '18',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: [
          { value: accuracy.toFixed(1), name: '准确' },
          { value: error.toFixed(1), name: '误差' }
        ]
      }
    ]
  }
})

// 特征分布柱状图
const featureDistributionOption = computed(() => {
  if (!selectedFeature.value || fileData.value.length === 0) {
    return { series: [] }
  }
  
  // 计算所选特征的分布
  const values = fileData.value.map(item => item[selectedFeature.value])
  const min = Math.min(...values)
  const max = Math.max(...values)
  const range = max - min
  const bucketCount = 10
  const bucketSize = range / bucketCount
  
  const buckets = Array(bucketCount).fill(0)
  values.forEach(value => {
    const bucketIndex = Math.min(Math.floor((value - min) / bucketSize), bucketCount - 1)
    buckets[bucketIndex]++
  })
  
  const bucketLabels = Array(bucketCount).fill(0).map((_, i) => {
    const start = min + i * bucketSize
    const end = min + (i + 1) * bucketSize
    return `${start.toFixed(1)}-${end.toFixed(1)}`
  })
  
  return {
    title: {
      text: `${selectedFeature.value} 分布`,
      left: 'center'
    },
    tooltip: {
      trigger: 'axis'
    },
    xAxis: {
      type: 'category',
      data: bucketLabels,
      axisLabel: {
        rotate: 45,
        interval: 0
      }
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '数量',
        type: 'bar',
        data: buckets
      }
    ]
  }
})

// 文件选择变化
const handleFileChange = async () => {
  await fetchFileData(selectedFile.value)
}

// 特征选择变化
const handleFeatureChange = () => {
  // 不需要重新获取数据，只需要更新图表
}

// 时间范围切换
const handleTimeRangeChange = () => {
  // 根据时间范围过滤数据
  fetchHistoryFiles()
}

// 初始化
onMounted(() => {
  fetchHistoryFiles()
})
</script>

<style scoped>
.dashboard {
  padding: 20px;
}

.stat-cards {
  margin-bottom: 20px;
}

.stat-card {
  height: 100%;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-value {
  font-size: 24px;
  font-weight: bold;
  margin: 10px 0;
}

.card-trend {
  display: flex;
  align-items: center;
  font-size: 14px;
  gap: 4px;
}

.card-trend.up {
  color: #67c23a;
}

.card-trend.down {
  color: #f56c6c;
}

.control-panel {
  margin-bottom: 20px;
}

.control-actions {
  display: flex;
  gap: 16px;
}

.chart-card {
  margin-bottom: 20px;
}

.chart-container {
  height: 400px;
}

.chart {
  height: 100%;
  width: 100%;
}
</style> 